// src/store/modules/auth.ts
import { defineStore } from 'pinia'
import type { User } from '@/types/user'

interface AuthState {
  user: User | null
  accessToken: string | null
  isAuthenticated: boolean
}

export const useAuthStore = defineStore('auth', {
  state: (): AuthState => ({
    user: null,
    accessToken: null,
    isAuthenticated: false
  }),

  getters: {
    currentUser: (state) => state.user
  },

  actions: {
    async login(username: string, password: string) {
      try {
        // 这里应该调用实际的登录 API
        // 为了演示，我们使用模拟数据
        const response = await new Promise<{ user: User; accessToken: string }>((resolve) => {
          setTimeout(() => {
            resolve({
              user: { id: 1, username, email: `${username}@example.com` },
              accessToken: 'mock_token_12345'
            })
          }, 1000)
        })

        this.setUser(response.user)
        this.setAccessToken(response.accessToken)
        this.isAuthenticated = true

        // 将 token 存储在 localStorage 中
        localStorage.setItem('auth_token', response.accessToken)
      } catch (error) {
        console.error('Login failed:', error)
        throw error
      }
    },

    logout() {
      this.user = null
      this.accessToken = null
      this.isAuthenticated = false
      localStorage.removeItem('auth_token')
    },

    async checkAuth() {
      const token = localStorage.getItem('auth_token')
      if (token) {
        try {
          // 这里应该调用实际的 API 来验证 token 并获取用户信息
          // 为了演示，我们使用模拟数据
          const response = await new Promise<User>((resolve) => {
            setTimeout(() => {
              resolve({ id: 1, username: 'testuser', email: 'testuser@example.com' })
            }, 1000)
          })

          this.setUser(response)
          this.setAccessToken(token)
          this.isAuthenticated = true
        } catch (error) {
          console.error('Token validation failed:', error)
          this.logout()
        }
      }
    },

    setUser(user: User | null) {
      this.user = user
    },

    setAccessToken(token: string | null) {
      this.accessToken = token
    }
  }
})
